package team.yidong.fenda.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.expression.Maps;
import team.yidong.fenda.entity.HospitalDepartment;
import team.yidong.fenda.entity.Master;
import team.yidong.fenda.entity.MasterScore;
import team.yidong.fenda.service.HospitalDepartmentService;
import team.yidong.fenda.service.HospitalService;
import team.yidong.fenda.service.MasterService;
import team.yidong.fenda.utils.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


@Controller
public class MasterController {
    @Autowired
    MasterService masterService;
    @Autowired
    HospitalService hospitalService;
    @Autowired
    ImageCheck imageCheck;
    @Autowired
    QiNiuYunUtil qiNiuYunUtil;
    @Autowired
    WxLoginUtil wxLoginUtil;
    @Autowired
    HospitalDepartmentService hospitalDepartmentService;

    @RequestMapping("/master")
    public String master(Model model, HttpSession session) {
        Integer hospitalId = (Integer) session.getAttribute("loginHospitalId");
        String sysName = (String) session.getAttribute("loginSysUserName");
        model.addAttribute("sysName", sysName);
        if (hospitalId != 1) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setExcludes((new String[]{"hospitalPermissionSet", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList"}));
            model.addAttribute("hospitals", JSONArray.fromObject(hospitalService.findHospitalById(hospitalId), jsonConfig));

        } else {
            JSONArray jsonArray = hospitalService.findAll();
            jsonArray.remove(0);
            model.addAttribute("hospitals", jsonArray);

        }
        return "master";
    }

    @RequestMapping("/findMaster")
    @ResponseBody
    public JSONObject findMaster(HttpSession session, String hospitalName, String name, String goodAt, Double scoreNum, String masterInfo, Integer offset, Integer limit) {
        Integer hospitalId = (Integer) session.getAttribute("loginHospitalId");
        return masterService.findMaster(hospitalId, hospitalName, name, goodAt, scoreNum, masterInfo, offset, limit);
    }

    @RequestMapping("/addMaster")
    @ResponseBody

    public String addUser(@RequestParam String name, @RequestParam String info, @RequestParam String goodAt, @RequestParam String hospitalName, @RequestParam String userName, @RequestParam String password, @RequestParam Integer departmentId, @RequestParam String phoneNum) {
        return masterService.addMaster(name, info, goodAt, hospitalName, userName, password, departmentId, phoneNum);

    }

    @RequestMapping("/updateMaster")
    @ResponseBody
    public String updateHospital(@RequestParam String jsonData) {
        JSONObject jsonObject = JSONObject.fromObject(jsonData);
        Map classMap = new HashMap();
        classMap.put("masterScoreSet", MasterScore.class);
        Master master = (Master) JSONObject.toBean(jsonObject, Master.class, classMap);

        masterService.updateMaster(master);
        return "修改成功";
    }

    @RequestMapping("/deleteMaster")
    @ResponseBody
    public String deleteHospital(@RequestParam String jsonData) {
        JSONArray jsonArray = JSONArray.fromObject(jsonData);
        Map classMap = new HashMap();
        classMap.put("masterScoreSet", MasterScore.class);
        Master[] masters = (Master[]) JSONArray.toArray(jsonArray, Master.class, classMap);
        List list = Arrays.asList(masters);
        masterService.deleteMaster(list);

        return "删除成功";
    }

    @RequestMapping("/updateMasterHeadImg")
    @ResponseBody
    public String updateMasterHeadImg(Model model, @RequestParam("imageFile") MultipartFile multipartFile, @RequestParam Integer masterId) {
        String fileName = new String();
        if (!multipartFile.isEmpty()) {
            try {
                if (imageCheck.isImage(multipartFile.getBytes())) {
                    // 获取文件的后缀名
                    fileName = multipartFile.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //uuid为文件命名
                    fileName = UUID.randomUUID() + suffixName;
                    qiNiuYunUtil.uploadFiles(multipartFile.getBytes(), fileName);
                } else {
                    return "不是图片文件";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
        } else {
            return "文件为空";
        }


        Master master = masterService.findById(masterId);
        master.setHeadImg("https://qny.liuxuanlong.xyz/" + fileName);
        masterService.updateMaster(master);
        return "上传成功";
    }

    @RequestMapping("/importMaster")
    @ResponseBody
    public String importMaster(@RequestParam("importFile") MultipartFile file) throws FileNotFoundException {

        //判断文件是否为空
        if (file == null) {
            return "文件不能为空";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //验证文件名是否合格
        if (!ExcelImportUtils.validateExcel(fileName)) {
            return ("文件必须是excel格式！");
        }
        //批量导入
        return masterService.importMaster(fileName, file);

    }

    /* @RequestMapping("/downloadFileModel")
     public void downloadFileModel(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) throws IOException {

         String filename = "专家信息模板.xlsx";

         if (filename != null) {
             *//* 在servlet中获得工程目录,为文件的存在目录 *//*
            String filePath = request.getServletContext().getRealPath("/WEB-INF/fileModel/");
            ;
            File file = new File(filePath + filename);

            if (file.exists()) {
                *//* 通知浏览器是个下载文件 *//*
                response.setContentType("application/x-msdownload");
                *//*
                 * Content-Disposition 的作用 当Content-Type 的类型为要下载的类型时 ,
				 * 这个信息头会告诉浏览器这个文件的名字和类型。attachment表示为附件
				 *//*
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));

				*//* 读文件 *//*
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath + filename)));

                OutputStream out = response.getOutputStream();
                byte[] buffer = new byte[2048];
                int len;
                while ((len = bis.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }

                bis.close();


            }

        }


    }
*/
    @RequestMapping("/findMasterById")
    @ResponseBody
    public JSONObject findMasterById(@RequestParam String masterInfoId) {
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "master", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", "answer", "praiseUserSet", "answerList", "question", "masterScoreAnswer", "masterAnswerList"});
        return JSONObject.fromObject(masterService.findById(Integer.parseInt(masterInfoId)), config);

    }

    @RequestMapping("/updateMasterInfo")
    @ResponseBody
    public void updateMasterInfo(String masterName, String masterInfo, String masterGoodAt, String masterUserName, String masterpassword, @RequestParam Integer masterId) {

        masterService.updateMasterInfo(masterId, masterName, masterGoodAt, masterInfo, masterUserName, masterpassword);
    }

    @RequestMapping("/findMasterUserName")
    @ResponseBody
    public String findMasterUserName(@RequestParam Integer masterId) {
        return masterService.findMasterUserName(masterId);
    }

    @RequestMapping("/findMasterByDepartmentId")
    @ResponseBody
    public JSONArray findMasterByDepartmentId(@RequestParam Integer departmentId) {
        return masterService.findMasterByHospitalDepartmentId(departmentId);
    }
}
